﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using PICOC.Silverlight.View.ReportBugServiceReference;

namespace PICOC.Silverlight.View
{
    public partial class MainPage : UserControl
    {
        private DispatcherTimer timer = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 0, 0, 500) };

        private bool _loaded;

        public MainPage()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            timer.Tick += new EventHandler(timer_Tick);
            modalReportBug.OnClose += new EventHandler(modalReportBug_OnClose);

            _loaded = true;
        }

        private void tbSyn_TextChanged(object sender, TextChangedEventArgs e)
        {
            recalculate();
        }

        private void tbElement_TextChanged(object sender, TextChangedEventArgs e)
        {
            recalculate();

            if (timer.IsEnabled)
            {
                timer.Stop();
            }
            timer.Start();
        }

        void timer_Tick(object sender, EventArgs e)
        {
            timer.Stop();
            paint();
        }

        private void paint()
        {
            clear();

            paint(tbPopulation.Text, (cbLegendPopulation.SelectedItem as Rectangle).Fill, warningPopulation);
            paint(tbIntervention.Text, (cbLegendIntervention.SelectedItem as Rectangle).Fill, warningIntervention);
            paint(tbComparison.Text, (cbLegendComparison.SelectedItem as Rectangle).Fill, warningComparison);
            paint(tbOutcome.Text, (cbLegendOutcome.SelectedItem as Rectangle).Fill, warningOutcome);
            paint(tbContext.Text, (cbLegendContext.SelectedItem as Rectangle).Fill, warningContext);

            tbQuestion.UpdateLayout();
        }

        private void clear()
        {
            tbQuestion.SelectAll();
            Paragraph para = new Paragraph();
            para.Inlines.Add(new Run() { Text = tbQuestion.Selection.Text });
            tbQuestion.Blocks.Clear();
            tbQuestion.Blocks.Add(para);
        }

        private void paint(String textElement, Brush brush, UIElement warning)
        {
            if (String.IsNullOrWhiteSpace(textElement))
                return;

            bool finded = false;

            int count = 0;
            while (true)
            {
                tbQuestion.SelectAll();
                TextSelection selection = tbQuestion.Selection;
                selection.Select(selection.Start.GetPositionAtOffset(count, LogicalDirection.Forward), selection.End);

                if (String.IsNullOrWhiteSpace(selection.Text.Trim()))
                    break;

                if (selection.Text.ToLower().StartsWith(textElement.ToLower()))
                {
                    selection.Select(selection.Start, selection.Start.GetPositionAtOffset(textElement.Length, LogicalDirection.Forward));
                    selection.ApplyPropertyValue(Run.ForegroundProperty, brush);
                    
                    finded = true;
                }

                count++;
            }

            warning.Visibility = finded ? Visibility.Collapsed : Visibility.Visible;
        }

        private void recalculate()
        {
            List<PICOCElement> elements = new List<PICOCElement>();

            aux(tbPopulation, ref elements, tbPopulationS1, tbPopulationS2, tbPopulationS3);
            aux(tbIntervention, ref elements, tbInterventionS1, tbInterventionS2, tbInterventionS3);
            aux(tbComparison, ref elements, tbComparisonS1, tbComparisonS2, tbComparisonS3);
            aux(tbOutcome, ref elements, tbOutcomeS1, tbOutcomeS2, tbOutcomeS3);
            aux(tbContext, ref elements, tbContextS1, tbContextS2, tbContextS3);

            PICOCStructure picoc = new PICOCStructure(elements.ToArray());

            String tx = picoc.CreateQuery();

            tbQuery.SelectAll();
            tbQuery.Selection.Text = tx;
        }

        private void aux(TextBox tb, ref List<PICOCElement> elements, TextBox s1, TextBox s2, TextBox s3)
        {
            if (!String.IsNullOrWhiteSpace(tb.Text))
            {
                List<String> syns = new List<string>();

                if (!String.IsNullOrWhiteSpace(s1.Text))
                    syns.Add(s1.Text.Trim());

                if (!String.IsNullOrWhiteSpace(s2.Text))
                    syns.Add(s2.Text.Trim());

                if (!String.IsNullOrWhiteSpace(s3.Text))
                    syns.Add(s3.Text.Trim());

                elements.Add(new PICOCElement(tb.Text.Trim(), syns.ToArray()));
            }
        }

        private void cbLegenda_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBox cb = (sender as ComboBox);
            cb.Background = (cb.SelectedItem as Rectangle).Fill;

            if(_loaded)
                paint();
        }

        private void btReportBug_Click(object sender, RoutedEventArgs e)
        {
            popUp.Visibility = Visibility.Visible;
            modalReportBug.btSend.IsEnabled = true;
        }

        void modalReportBug_OnClose(object sender, EventArgs e)
        {
            popUp.Visibility = Visibility.Collapsed;
        }
    }
}
